<template>

  <el-dialog :title="form.id?&quot;立即编辑&quot;:&quot;立即添加&quot;" :visible="showEditDialog" @close="closeFn">
    <el-form ref="forms" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item v-if="!form.id" label="密码" prop="password">
        <el-input v-model="form.password" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="editFn">{{ form.id?"立即编辑":"立即添加" }}</el-button>
        <el-button @click="closeFn">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { getEmployeesRole, editUser, addUser } from '@/api/employees'
export default {
  props: {
    showEditDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        username: '',
        email: '',
        password: ''
      },
      //   表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在3~~~5个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在6~~~12个数字', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  methods: {
    // 编辑确认按钮
    async editFn() {
      await this.$refs.forms.validate() // 表单验证
      //   console.log(666);
      if (!this.form.id) {
        // console.log(111, this.form);
        await addUser(this.form)
      } else {
        await editUser(this.form) // 编辑
      }
      //   console.log(57, res);
      this.closeFn() // 弹框显示隐藏
      this.$message.success('编辑成功')
    },
    // 弹框显示隐藏
    closeFn() {
      this.$emit('update:showEditDialog', false) // 隐藏
      this.form = {
        // 清空表单
        username: '',
        email: ''
      }
      this.$refs.forms.resetFields() // 清空表单规则
      //   this.$message.info('取消成功!'); //提示
      this.$emit('getEmployeesUser') // 调用父组件重新调用全部用户信息函数刷新页面
    },
    // 获取指定用户信息
    async getEmployeesRole(id) {
      const res = await getEmployeesRole(id)
      console.log(58, res)
      this.form = res
    }
  }
}
</script>

<style>
</style>
